package com.bac.bacplatform;

import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.bac.http.VolleyErrorHelper;
import com.bac.http.VolleyErrorHelper.CommenErrorHandler;
import com.bac.javabeans.Principal;
import com.bac.utils.Config;
import com.bac.utils.Storage;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends FragmentActivity implements OnClickListener,
		ErrorListener, CommenErrorHandler {

	public static final String UPDATE_ACTION = "update_personal_Action";

	private Fragment fragmentHome, fragmentHall, fragmentPersonal;
	private ImageView imageView1, imageView2, imageView3,imageView4;
	private TextView textView1, textView2, textView3,textView4;

	private UpdateBroadCast mBroadCast;

	 private boolean mIsLogin = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		BacApplication.getInstance().addActivity(this);

		imageView1 = (ImageView) findViewById(R.id.imageView1);
		imageView2 = (ImageView) findViewById(R.id.imageView2);
		imageView3 = (ImageView) findViewById(R.id.imageView3);
		imageView4 = (ImageView) findViewById(R.id.imageView_card);

		textView1 = (TextView) findViewById(R.id.textview1);
		textView2 = (TextView) findViewById(R.id.textview2);
		textView3 = (TextView) findViewById(R.id.textview3);
		textView4 = (TextView) findViewById(R.id.textview_card);

		findViewById(R.id.linearLayout1).setOnClickListener(this);
		findViewById(R.id.linearLayout2).setOnClickListener(this);
		findViewById(R.id.linearLayout3).setOnClickListener(this);
		findViewById(R.id.linearLayout4).setOnClickListener(this);

		fragmentHome = new FragmentHome();
		fragmentHall = new FragmentHall();
		fragmentPersonal = new FragmentPersonal();

		getSupportFragmentManager().beginTransaction()
				.add(R.id.fragment_content, fragmentHome).hide(fragmentHall)
				.hide(fragmentPersonal).commit();

		autoLogin();
		Log.i("MainActivity---", "onCreate--");

		mBroadCast = new UpdateBroadCast();

	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.i("MainActivity---", "onRestart--");
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Log.i("MainActivity---", "onNewIntent--");
		// mIsLogin = intent.getBooleanExtra("islogin", false);
//		goHome();
	}

	public void goHome() {
		FragmentTransaction trx = getSupportFragmentManager()
				.beginTransaction();
		trx.hide(fragmentHall).hide(fragmentPersonal);
		if (!fragmentHome.isAdded()) {
			trx.add(R.id.fragment_content, fragmentHome);
		}
		trx.show(fragmentHome).commit();
		mIsLogin = false;
		imageButtonChange(1);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("MainActivity---", "onResume--");
	}

	@Override
	protected void onStart() {
		super.onStart();
		registerBoradcastReceiver();
		Log.i("MainActivity---", "onStart--");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			unregisterReceiver(mBroadCast);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Log.i("MainActivity---", "onDestroy--");
	}

	@Override
	public void onClick(View v) {
		FragmentTransaction trx = getSupportFragmentManager()
				.beginTransaction();
		switch (v.getId()) {
		case R.id.linearLayout1:
			// if (textView1.getText().toString().equals("交通生活")) {
			// trx.hide(fragmentHome).hide(fragmentPersonal);
			// if (!fragmentHall.isAdded()) {
			// trx.add(R.id.fragment_content, fragmentHall);
			// }
			// trx.show(fragmentHall).commit();
			// } else {
			trx.hide(fragmentHall).hide(fragmentPersonal);
			if (!fragmentHome.isAdded()) {
				trx.add(R.id.fragment_content, fragmentHome); 
			}
			trx.show(fragmentHome).commit();
			// }
			imageButtonChange(1);
			break;
		case R.id.linearLayout2:
			if (!mIsLogin) {
				hanlderAutorError();
			}else{
				if (Config.UserGeneralInfo.wealthAccountBanding) {
					Intent intentToMyWallet = new Intent(this,MyWalletActivity.class);
					startActivity(intentToMyWallet);
				}else{
					Intent intentToFindPink = new Intent(this, FindPickActivity.class);
					startActivity(intentToFindPink);
				}
			}
			
			break;
		case R.id.linearLayout3:
			trx.hide(fragmentHome).hide(fragmentHall);
			if (!fragmentPersonal.isAdded()) {
				trx.add(R.id.fragment_content, fragmentPersonal);
			}
			trx.show(fragmentPersonal).commit();
			imageButtonChange(3);
			break;
		case R.id.linearLayout4:
			if (!mIsLogin) {
				hanlderAutorError();
			} else {
				// trx.hide(fragmentHome).hide(fragmentPersonal);
				// if (!fragmentHall.isAdded()) {
				// trx.add(R.id.fragment_content, fragmentHall);
				// }
				// trx.show(fragmentHall).commit();
				// imageButtonChange(4);

				Intent intent = new Intent();
				intent.setAction("android.intent.action.VIEW");
				Uri url = Uri.parse("http://wechat.bac365.com/wx/card/upload");
				intent.setData(url);
				startActivity(intent);
			}
			break;

		default:
			break;
		}
	}

	public void autoLogin() {
		String username = Storage.getString(getApplicationContext(),
				Config.USER_ACCOUNT_KEY);
		String pwd = Storage.getString(getApplicationContext(),
				Config.USER_PWD_KEY);
		
		if (username.length() == 0 || pwd.length() == 0){
			return;
		}
		
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Util.dismissProgressDialog();
				HashMap<String, String> result = new Gson().fromJson(
						new String(response),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("code")) {
					mIsLogin = false;
					hanlderErrorShowMessage(result.get("msg"));
				}else{
					mIsLogin = true;
					Log.i("MainActivity----success",
							"succes++++" + response.toString());
					Gson gson = new Gson();
					Principal principal = gson.fromJson(response, Principal.class);
					// 设置全局个人信息
					Config.UserGeneralInfo.setUserInfo(principal);
				}
			}
		};
		Util.showProgressDialog(this);
		String path = Config.URL_LOGIN;
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", username);
		map.put("password", pwd);
		map.put("gesture", "false");
		Util.httpStringPost(path, sL, this, map);

	}
	
	public void getCurrentuser() {
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.i("MainActivity--getCurrentuser----success", response.toString());
				Gson gson = new Gson();
				Principal principal = gson.fromJson(response, Principal.class);
				Config.UserGeneralInfo.setUserInfo(principal);
			}
		};
		
		String path = Config.URL_CURRENT_USER;
		Util.httpRequestToGet(path, sL, this);
	}

	private void imageButtonChange(int i) {

		imageView1.setImageDrawable(getResources().getDrawable(
				R.drawable.home_icon_navbar_home_normal));

		imageView2.setImageDrawable(getResources().getDrawable(
				R.drawable.home_icon_navbar_businesshall_normal));
		imageView3.setImageDrawable(getResources().getDrawable(
				R.drawable.home_icon_navbar_my_normal));
		imageView4.setImageDrawable(getResources().getDrawable(
				R.drawable.home_gas_card_off));

		textView1.setTextColor(getResources().getColor(
				R.color.menu_bar_textgray));
		textView2.setTextColor(getResources().getColor(
				R.color.menu_bar_textgray));
		textView3.setTextColor(getResources().getColor(
				R.color.menu_bar_textgray));
		textView4.setTextColor(getResources().getColor(
				R.color.menu_bar_textgray));

		if (i == 1) {
			// if (textView1.getText().toString().equals("交通生活")) {
			// imageView1.setImageDrawable(getResources().getDrawable(
			// R.drawable.home_icon_navbar_home_normal));
			// textView1.setText("首页");
			imageView1.setImageDrawable(getResources().getDrawable(
					R.drawable.home_icon_navbar_home_focus));
			textView1.setTextColor(getResources().getColor(
					R.color.menu_bar_textred));
			// } else {
			// imageView1.setImageDrawable(getResources().getDrawable(
			// R.drawable.jiaotong_life_2));
			// textView1.setText("交通生活");
			// }
		} else if (i == 2) {
			/*
			 * imageView2.setImageDrawable(getResources().getDrawable(
			 * R.drawable.home_icon_navbar_businesshall_focus));
			 * textView2.setTextColor(getResources().getColor(
			 * R.color.menu_bar_textred));
			 */
		} else if (i == 3) {
			imageView3.setImageDrawable(getResources().getDrawable(
					R.drawable.home_icon_navbar_my_focus));
			textView3.setTextColor(getResources().getColor(
					R.color.menu_bar_textred));
		}else if (i == 4) {
			imageView4.setImageDrawable(getResources().getDrawable(
					R.drawable.home_gas_card_on));
			textView4.setTextColor(getResources().getColor(
					R.color.menu_bar_textred));
		}
	}

	public void goToLogin() {
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
//		finish();
	}

	@Override
	public void hanlderTimeoutError() {
		Log.e("MainActivity----", "hanlderTimeoutError");
	}

	@Override
	public void hanlderErrorShowMessage(String message) {
		Log.e("MainActivity----", "hanlderErrorShowMessage " + message);
		AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Custom_dialog);
		final AlertDialog alertDialog = builder.create();
//		alertDialog.setCanceledOnTouchOutside(false);
		alertDialog.show();
		Window window = alertDialog.getWindow();
		View view = LayoutInflater.from(this).inflate(R.layout.dialog_alert, null);
		((TextView)(view.findViewById(R.id.tv_title))).setText("提示");
		((TextView)(view.findViewById(R.id.tv_message))).setText(message);
		view.findViewById(R.id.ly_ok).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		window.setContentView(view);
		window.setLayout((int)(Util.getWidth(getApplicationContext()) * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
		
	}

	@Override
	public void hanlderAutorError() {
		Log.e("MainActivity----", "hanlderAutorError");
//		AlertDialog.Builder builder = new AlertDialog.Builder(this,
//				R.style.Custom_dialog);
//		final AlertDialog alertDialog = builder.create();
//		alertDialog.setCanceledOnTouchOutside(false);
//		alertDialog.show();
//		Window window = alertDialog.getWindow();
//		View view = LayoutInflater.from(this).inflate(R.layout.dialog_alert,
//				null);
//		view.findViewById(R.id.ly_cancel).setVisibility(View.VISIBLE);
//		view.findViewById(R.id.line).setVisibility(View.VISIBLE);
//
//		((TextView) (view.findViewById(R.id.tv_title))).setText("提示");
//		TextView messageTV = (TextView) view.findViewById(R.id.tv_message);
//		messageTV.setText("现在就去登录");
//
//		view.findViewById(R.id.ly_cancel).setOnClickListener(
//				new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						alertDialog.dismiss();
//					}
//				});
//
//		view.findViewById(R.id.ly_ok).setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				alertDialog.dismiss();
//				goToLogin();
//			}
//		});
//		window.setContentView(view);
//		window.setLayout((int) (Util.getWidth(this) * 0.8),
//				WindowManager.LayoutParams.WRAP_CONTENT);
		goToLogin();
	}

	@Override
	public void hanlderUnknowError() {
		Log.e("MainActivity----", "hanlderUnknowError");
	}

	@Override
	public void hanlderNetworkError() {
		Log.e("MainActivity----", "hanlderNetworkError");
		Toast.makeText(getApplicationContext(), "网络异常", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		Util.dismissProgressDialog();
		VolleyErrorHelper.handleServerError(error, this);
	}

	public void registerBoradcastReceiver() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(UPDATE_ACTION);
		registerReceiver(mBroadCast, intentFilter);
	}

	private class UpdateBroadCast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(UPDATE_ACTION)) {
				Log.i("UpdateBroadCast---", "get broadcast to update");
				if (!fragmentPersonal.isHidden()) {
					((FragmentPersonal) fragmentPersonal).getCurrentuser();
				}
			}
		}
	}
	
	private long firstTime = 0;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
				
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 1500) {// 
				Toast.makeText(MainActivity.this, "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				firstTime = secondTime;// 
				return true;
			} else {
				BacApplication.getInstance().exit(); 
			}
			return true;
			
		}
		return super.onKeyDown(keyCode, event);
	}
}
